<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./header.js"></script>
  <script src="./data.js"></script>
</head>

<body>

  <script src="./header-core.js"></script>
  <script>
    const header11 = HeaderCore.create(headerConfig, data)
    console.log('生成的表头树：', header11)
    /**
     * 获取合并列的数量
     * @param {*} data 
     * @returns 
     */
    function getColumnCount(data) {
      let count = 0;
      if (!data) return count;
      const { children } = data;
      if (!children) return count;
      for (let i = 0, len = children.length; i < len; i++) {
        count += children[i].children ? getColumnCount(children[i]) : 1;
      }
      return count;
    }
    /**
     * 检测列表是否存在下一级
     * @param {array} data 
     * @returns {boolean}
     */
    function isHaveChildren(data) {
      if (!data) return false;
      for (let i = 0, len = data.length; i < len; i++) {
        let item = data[i];
        if (Array.isArray(item.children) && item.children.length > 0) {
          return true;
        }
      }
      return false;
    }

    const getHeader = (dataTee) => {
      const _d = JSON.parse(JSON.stringify(dataTee));
      let resultGroup = {};
      const _walk = (data, __level = 1) => {
        const groupKey = `level_${__level}`;
        const isHaveChild = isHaveChildren(data);
        for (let i = 0, len = data.length; i < len; i++) {
          const column = data[i];
          // 是否存在子集
          if (column.children && column.children.length) {
            column.rowspan = 1;
            column.columnspan = getColumnCount(column);
            _walk(column.children, __level + 1); // 继续往下走
          } else {
            column.rowspan = isHaveChild ? data.length : 1;
            column.colspan = 1;
          }
          if (!resultGroup[groupKey]) {
            resultGroup[groupKey] = []
          }
          resultGroup[groupKey].push(column)
        }
        return resultGroup;
      }
      return Object.keys(_walk(_d))
        .sort()
        .map(key => resultGroup[key])
    }
    const header = getHeader(header11);
    console.log(header)
  </script>
</body>

</html>